const jwt = require('jsonwebtoken');
const { Role } = require('../models');
const sequelize = require('sequelize');

class RoleService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter, page = 1, page_size = 20) {
		const { name } = filter;
		const where = {};
		if (name) where['name'] = { [sequelize.Op.like]: `%${name}%` };

		const { count: total, rows: data } = await Role.findAndCountAll({
			where,
			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['id', 'desc']
			]
		});

		return {
			data,
			total
		}
	}

	async info(where) {
		return Role.findOne({
			where
		});
	}

	async delete(id) {
		return Role.destroy({
			where: {
				id: { [sequelize.Op.in]: String(id).split(',') }
			}
		});
	}

	async save(params) {
		const { id } = params;
		['create_time', 'update_time', 'delete_time'].forEach((d) => {
			delete params[d];
		});

		if (typeof params.auth === 'string') {
			params.auth = JSON.parse(params.auth);
		}

		if (id) {
			await Role.update(params, {
				where: {
					id
				}
			})
			return Role.findByPk(id);
		} else {
			return Role.create(params);
		}
	}
}

exports = module.exports = RoleService;
